package com.yata.utils.controller;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yata.utils.html.HtmlConverter;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.handler.MatchableHandlerMapping;

@RestController
public class HomeController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${filepath}")
    String filepath;

    @Value("${uploadFilePath}")
    String uploadFilePath;

    @Value("${resultFilePath}")
    String resultFilePath;

    @PostMapping("/js2html")
    public String js2html(@RequestParam(value = "js") String js) throws IOException {
        String html = HtmlConverter.getPureHtmlFromJSString(js);

        Document doc = Jsoup.parseBodyFragment(html);

        doc.outputSettings().indentAmount(4);

        String formatHtml = doc.body().children().outerHtml();

        return formatHtml;
    }

    @PostMapping("/html2js")
    public String html2js(@RequestParam(value = "html") String html) throws IOException {
        Document doc = Jsoup.parseBodyFragment(html);

        doc.outputSettings().indentAmount(4);

        String formatHtml = doc.body().children().outerHtml();

        String js = HtmlConverter.getJSFromHtmlString(formatHtml);

        return js;
    }

    @PostMapping("/uploadFile")

    public String upload(@RequestParam(value = "file") MultipartFile dropimage) throws IOException {
        try {
            String uuid = UUID.randomUUID().toString();
            String targetFile = uploadFilePath + uuid + dropimage.getOriginalFilename();
            File file = new File(targetFile);
            byte[] fileStream = IOUtils.toByteArray(dropimage.getInputStream());
            //复制流到目标文件
            FileUtils.writeByteArrayToFile(file, fileStream);
            Map<String, Object> result = new HashMap<>();
            result.put("retcode", 1000);
            result.put("path", targetFile);
            JSONObject json = new JSONObject(result);
            return json.toString();
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("retcode", 1001);
            result.put("retmsg", e.getMessage());
            JSONObject json = new JSONObject(result);
            return json.toString();
        }


    }

    @PostMapping("/fanyi")
    public String fanyi(@RequestParam(value = "msg") String msg, @RequestParam(value = "type") String type) throws IOException {

        System.out.println(type);
        String result = new HttpClient4Tools().fanyiByBaidu(msg);
        String returnData = "";
        if (result != null) {
            JSONObject json = new JSONObject(result);
            JSONArray jsonArray = json.getJSONArray("trans_result");
            System.out.println("jsonArray：" + jsonArray);
            JSONObject jj = (JSONObject) jsonArray.get(0);
            String dst = (String) jj.get("dst");
            switch (type) {
                case "4":
                    returnData = Tools.coverToHump(dst);
                    break;
                case "3":
                    returnData = Tools.cover(dst);
                    break;
                case "2":
                    returnData = Tools.coverToUpWord(dst);
                    break;
                case "1":
                    returnData = Tools.coverToLower(dst);
                    break;
            }

        }

        return returnData;
    }

    @PostMapping("/transformation")
    public String transformation(
            @RequestParam(value = "imgpath") String imgpath,
            @RequestParam(value = "font") String font,
            @RequestParam(value = "fontStyle") String fontStyle,
            @RequestParam(value = "fontcolor") String fontcolor,
            @RequestParam(value = "fontsize") String fontsize,
            @RequestParam(value = "coordinateX") String coordinateX,
            @RequestParam(value = "color_r") String color_r,
            @RequestParam(value = "color_g") String color_g,
            @RequestParam(value = "color_b") String color_b,
            @RequestParam(value = "coordinateY_left") String coordinateY_left,
            @RequestParam(value = "coordinateY_right") String coordinateY_right
    ) throws IOException {
        logger.info("合成图片；【{}】", imgpath);
        logger.info("写入的文字；【{}】【{}】", font,fontsize);
        PictureWithWord pww = new PictureWithWord();

        BufferedImage d = pww.loadImageLocal(imgpath);

        int startHeight = 100;
//        switch (coordinate) {
//            case "1":
//                startHeight = (int)Math.ceil(d.getHeight() * (1d/3));
//                break;
//            case "2":
//                startHeight =(int)Math.ceil(d.getHeight() * (2d / 3));
//                break;
//            case "3":
//                startHeight = d.getHeight() - 100;
//                break;
//
//        }
        logger.info("写入图片中位置；【{}】", d);
        logger.info("写入图片中位置；【{}】", startHeight);
        Color fontColor = Color.RED;
        if ("".equals(color_r) && "".equals(color_g) && "".equals(color_b)) {
            switch (fontcolor) {
                case "1":
                    fontColor = Color.RED;
                    break;
                case "2":
                    fontColor = Color.BLUE;
                    break;
            }
        } else  {
            logger.info("用户自定义颜色；【{}，{},{}】", color_r,color_g,color_b);
            fontColor =  new Color(getInt(color_r), getInt(color_g),getInt(color_b));
        }



        String fontStyleFinal = "楷书";
        switch (fontStyle) {
            case "1":
                fontStyleFinal = "楷书";
                break;
            case "2":
                fontStyleFinal = "宋体";
                break;
            case "3":
                fontStyleFinal = "Source Han Sans SC Normal";
                break;
            case "4":
                fontStyleFinal = "Source Han Sans SC Bold";
                break;
            case "5":
                fontStyleFinal = "Source Han Sans SC Bold";
                break;
        }

        PictureWithWord tt = new PictureWithWord();
        tt.setGlobalFont(fontStyleFinal, Font.TRUETYPE_FONT,  Integer.parseInt(fontsize));
        String fileName = imgpath.substring(imgpath.lastIndexOf("/") + 1, imgpath.length());
        String targerFilePath = filepath + fileName;
        String resultFilePathFinal = resultFilePath + fileName;
        logger.info("targerFilePath: " + fileName);
        tt.writeImageWithWord(imgpath, targerFilePath,
                font, getInt(coordinateY_left), getInt(coordinateY_right),
                getInt(coordinateX), 10, fontColor);


        return resultFilePathFinal;
    }

    private int getInt(String param){
        try{
            return Integer.parseInt(param);
        }catch (Exception e){
            return 0;
        }
    }


}
